package com.zhf.servlet;

import com.zhf.bean.Administrator;
import com.zhf.service.AdministratorService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: ZhaoHuanfeng
 * @Date: 2020/10/17 15:25
 */
@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端传来的数据
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        System.out.println("获取到的用户名为:"+userName);
        System.out.println("获取到的密码为:"+password);
        //创建UserService类型的对象实现数据校验功能
        AdministratorService administratorService = new AdministratorService();
        Administrator administrator = administratorService.LoginService(new Administrator(userName, password));
        if (administrator==null){
            System.out.println("用户名或密码错误，登录失败");
            //实现服务器跳转,携带当前request和response跳转到当前页面
            //服务器跳转request共享
            request.setAttribute("error","用户名或密码错误，登录失败");
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("login.jsp");
            requestDispatcher.forward(request,response);
        }else {
            System.out.println("登录成功，欢迎使用！");
            //将登录成功的用户信息存入session中
            request.getSession().setAttribute("user",administrator);

            //配置实效为一周的session
            Cookie cookie = new Cookie("user", userName);
            cookie.setMaxAge(604800);
            response.addCookie(cookie);

            //登录成功跳转到系统里面
            response.sendRedirect("menu.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
